<?
global $limit,$set_ads_per_page,$ads_tbl,$cat_tbl,$usr_tbl,$opt_tbl,$sel_tbl;
global $q_tbl,$offset,$set_list_img,$set_list_img_fp,$set_currency_text;
global $set_general_override,$set_fav_override,$set_bestrated_override;
global $set_latest_override,$set_frontpage_override,$set_premium_limit;
global $set_myitems_override,$set_top_override,$set_search_override,$set_mostviewed_override;
global $set_top_override,$set_validation,$cat_tpl,$set_language,$set_seperator,$sel_tbl,$lookupid,$set_multilang_opt;

define('OFFSET_TOKEN','<OFFSET>');

if (!$ads_tbl)
{
	echo "Critical Error.";
	exit;
}

// Some declarations, just to be sure
$val_string = "";
$color = "";
$count_ads = 0;
$ascdesc = "desc";
$catid = 0;
$navstr="";
$servicios = false;
$extraSortOrder="";
//JMR esta variable la cree para que contenga los "#tabs-1" finales en los links, así se mantiene el orden del buscador
$tablink="";
//JMR: banner por categoria
$bannerHid="";
//JMR: Category Path
$categoryPath = "";
$redirect_tipo_param="";


//JMR: descomentar estos campos para tomar mediciones de cuanto tarda en ejecutarse el while, y cada elemento 
//$tiempo=0;
//$time_start=0;
//$time_end=0;

// Get important input values
$order  = cleanInput(getParam("order","")); // Guest chooseable sort order


$way    = getParamInt("way",""); // Way to sort the result (1 or 0 allowed)
$offset = getParamInt("offset",0); // Start listing at sql position
if (!$offset || $offset<0)
	$offset=0;
$til = round($set_ads_per_page);	 // Default number of ads per page
$do_search=getParam("do_search",""); // Find out if search mode
if (getParam("searchword","")!="")
	$do_search=getParam("searchword","");

$catid_search=getParamInt("catid_search",""); //Search for cat_id
$catid=getParamInt("catid","ID_CAT_COMPRA"); //Category id
$user_id=getParamInt("user_id",""); // Get ads for a special user

if ($catid=="")
	$catid=$lookupid;

if (!$useritems AND !$lDoNotCreateTemplate) // Template object is already created from include sometimes
	$tplList = new TplLoad;

$fArray = array();
$tplList->assign("catid",$catid);

if (!isset($allowads))
	$allowads = "";
if (!isset($par_list))
	$par_list = "";
if (!isset($useritems))
	$useritems = "";

$val_string="";
if ($set_validation) // If ad validation is on, only show ad_is_valid=1 ads
	$val_string = " AND ad_is_validated = 1";
/*JMR: validación de avisos no PAGOS */
$val_string .= " AND ad_enabled = 1";	



if ($order=="picture")
	$order="ad_has_picture";

if ($way) {
	if ($way==1)
		$ascdesc = "asc";
	elseif ($way==0)
		$ascdesc = "desc";
	else 
		$ascdesc = "desc";
}
else
	$ascdesc = "desc";


if (!$order AND !isset($mostviewed)) {
		$order = "ad_id";
}

$lToDbOrder=strToDb($order);


// Get field templates, if any...
$sql = "select cat_tpl from $cat_tbl where cat_id = '".$catid . "' limit 1";
$result_1 = q($sql);
$row_cat = mysql_fetch_array($result_1);
$cattpl = $row_cat["cat_tpl"];	

/*HEADER EXTRA FIELDS*/
$lSqlGetQuestions = "select * from $q_tbl where q_ad_list=1 AND (q_tpl=1 OR q_tpl='$cattpl') order by q_seq asc";
$result = q($lSqlGetQuestions);

$extra_fields_listing = '';
$extra_fields_query_addition_fields = '';
$extra_fields_query_addition_joins = '';
$count_extra_fields = 0;
//JMR: Extra Options for table MVIAL_AD: marca, modelo, etc
$extra_options_mvial =' left join (select a.mv_ad_id,a.mv_modelo,a.mv_potencia,a.mv_hskms,CAST(a.mv_anio AS SIGNED) AS mv_anio,b.marca,a.mv_marca_str,a.mv_localidad_name,a.mv_package_id from mvial_ad_extra_options a left join marca b ON a.mv_marca=b.id) mv ON '.$ads_tbl.'.ad_id=mv.mv_ad_id ';
$extra_options_mvial_full =' left join (select a.mv_ad_id,a.mv_modelo,a.mv_potencia,a.mv_hskms,CAST(a.mv_anio AS SIGNED) AS mv_anio,b.marca,a.mv_marca_str,a.mv_package_id from mvial_ad_extra_options a left join marca b ON a.mv_marca=b.id) mv ON '.$ads_tbl.'.ad_id=mv.mv_ad_id left join provincia pr ON '.$ads_tbl.'.ad_provincia = pr.id ';
//END JMR
$lLangSelected=$set_language;

// Determine what Option column to get data from 
$lLangSupportedArray=split(",",$set_multilang_opt);
//Marcas de Tiempo
if(isset($time_start))
	$time_start = microtime(true);
foreach ($lLangSupportedArray as $lItem)
{
	if ($lLangSelected==$lItem)
	{
		$lLangOptToSupport="opt_" . $lItem;
		$lOptCol=$lLangOptToSupport;
	}
}
//Marcas de Tiempo
if(isset($tiempo)){
	$time_end = microtime(true);
	$tiempo = $tiempo+($time_end-$time_start); 
}

if (!$lOptCol) // If the selected language doesn't have data, use default
	$lOptCol="opt_name";

//Marcas de Tiempo
if(isset($time_start))
	$time_start = microtime(true);
while ($lRowQ = mysql_fetch_array($result))
{
	$lArrayJoinFields[$count_extra_fields]["type"]=$lRowQ["q_type"];
	$lArrayJoinFields[$count_extra_fields]["caption"]=constant($lRowQ["q_question"]);
	$lArrayJoinFields[$count_extra_fields]["field"]=$count_extra_fields;
	$lArrayJoinFields[$count_extra_fields]["id"]="sel_option_text" . $count_extra_fields;
	
    //$extra_fields_listing .= "<th><a class='navlink' href='?catid=$catid&order=sel_option_text".$count_extra_fields."&way=$way{$url_heading}'  title='Sort by '>".constant($lRowQ["q_question"])."</a></th>";
    if ($extra_fields_query_addition_fields != "")
        $extra_fields_query_addition_fields .= ' , ';

    if ($lRowQ["q_type"]=="s" || $lRowQ["q_type"]=="r") // If select box or radio boxes
    	$extra_fields_query_addition_fields .= ' opt'.$count_extra_fields.'.'.$lOptCol.' as sel_option_text'.$count_extra_fields;
    elseif ($lRowQ["q_type"]=="c") // If checkbox
    	$extra_fields_query_addition_fields .= ' GROUP_CONCAT(opt'.$count_extra_fields.'.'.$lOptCol.' ORDER BY opt'.$count_extra_fields.'.opt_name ASC SEPARATOR ", ") as sel_option_text'.$count_extra_fields;
   	elseif ($lRowQ["q_type"]=="p") // If price
    	$extra_fields_query_addition_fields .= ' s'.$count_extra_fields.'.sel_option_decimal as sel_option_text'.$count_extra_fields . ",1 as sel_price".$count_extra_fields;
	elseif ($lRowQ["q_type"]=="j" || $lRowQ["q_type"]=="a") // If marca
    	$extra_fields_query_addition_fields .= ' concat(COALESCE(opt'.$count_extra_fields.'.marca,""),REPLACE(s'.$count_extra_fields.'.sel_option_text,"marca","")) as sel_option_text'.$count_extra_fields;
    else // If plan text fields
    	$extra_fields_query_addition_fields .= ' s'.$count_extra_fields.'.sel_option_text as sel_option_text'.$count_extra_fields;
       
    if($lRowQ["q_type"]=="j" || $lRowQ["q_type"]=="a"){
    $extra_fields_query_addition_joins .= ' left join '.$q_tbl.' q'.$count_extra_fields.'
                                              on q'.$count_extra_fields.'.q_field = '.$lRowQ["q_field"].'
                                            left join '.$sel_tbl.' s'.$count_extra_fields.'
                                              on s'.$count_extra_fields.'.sel_option_ad = '.$ads_tbl.'.ad_id
                                             and q'.$count_extra_fields.'.q_field = s'.$count_extra_fields.'.sel_option_field
                                          LEFT JOIN marca opt'.$count_extra_fields.' ON s'.$count_extra_fields.'.sel_option_id=opt'.$count_extra_fields.'.id 
	';
        if ($order == 'marca') {
            $lToDbOrder = 'opt'.$count_extra_fields.'.marca';
        }
    }else
    $extra_fields_query_addition_joins .= ' left join '.$q_tbl.' q'.$count_extra_fields.'
                                              on q'.$count_extra_fields.'.q_field = '.$lRowQ["q_field"].'
                                            left join '.$sel_tbl.' s'.$count_extra_fields.'
                                              on s'.$count_extra_fields.'.sel_option_ad = '.$ads_tbl.'.ad_id
                                             and q'.$count_extra_fields.'.q_field = s'.$count_extra_fields.'.sel_option_field
                                          LEFT JOIN '.$opt_tbl.' opt'.$count_extra_fields.' ON s'.$count_extra_fields.'.sel_option_id=opt'.$count_extra_fields.'.opt_id 
	';
    
    $count_extra_fields++;
}
//Marcas de Tiempo
if(isset($tiempo)){
	$time_end = microtime(true);
	$tiempo = $tiempo+($time_end-$time_start); 
	//Marcas de Tiempo 
}

if ($extra_fields_query_addition_fields=="")
	$extra_fields_query_addition_fields="0";
$tplList->assign("extra_fields_listing" , $extra_fields_listing);
/*END OF HEADER FIELDS*/


/* REGION SUPPORT */
$lRegionId=getParamInt("region","");
if (!$lRegionId)
	if ($_SESSION["region"]!=null)
		$lRegionId=round($_SESSION["region"]);

if ($lRegionId>0)
{
	$_SESSION["region"]=$lRegionId;
	$lRegionList=substr(getSubRegions($lRegionId,""),0,-1);
	if ($lRegionList=="")
		$lRegionList=$lRegionId;
	elseif ($lRegionId>0) 
		$lRegionList.=$lRegionList . "," . $lRegionId;
	$lRegionSqlAddon=" AND ad_region IN ($lRegionList) ";
}
elseif ($lRegionId==-1)
{
	$_SESSION["region"]="";
}

/* END OF REGION*/

if (isset($fp))
{
	//JMR: Corrección para los links de ordenamiento y siguiente: 19-06-2009
	if($catid==ID_CAT_COMPRA){
		$tablink="#tabs-1";		
	}else if($catid==ID_CAT_ALQUILER){
		$tablink="#tabs-2";		
	}else if($catid==ID_CAT_SERVICIOS){
		$tablink="#tabs-3";	
	}	
	//JMR
	// Frontpage
	$fixedOrder = "ad_is_premium DESC, ad_is_special DESC, "; //Este orden debe imponerse ante cualquier otro
	if (isset($set_latest_override))
	{
		// Custom setting from webmaster
		if ($set_frontpage_override>0) 
		{
			$til = $set_frontpage_override;	
			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_frontpage_override;
		}
	}

	if($catid == 0) $catid=ID_CAT_COMPRA;
	$extra_fields_query_addition_fields=0;
	if(!$catid){
		$catid = ID_CAT_COMPRA;
	}
	//$filtroPorMercado="and (cat_fatherid=$catid or cat_fatherid in (select cat_id from mvial_category where cat_fatherid=$catid))";
	$filtroPorMercado="";
	if($catid == ID_CAT_SERVICIOS){
		$servicios=true;
		$filtroPorMercado=" and cat_fatherid=".ID_CAT_SERVICIOS." ";
	}else{
		$filtroPorMercado=" and cat_fatherid!=".ID_CAT_SERVICIOS." ";
	}
	
	$sql_string = "select *,$extra_fields_query_addition_fields from $cat_tbl,$usr_tbl,$ads_tbl ".
	"$extra_fields_query_addition_joins $extra_options_mvial_full where cat_id=ad_cat_id AND user_id=ad_owner $val_string ".
	"$lRegionSqlAddon ".$filtroPorMercado." group by ad_id order by $fixedOrder $lToDbOrder $ascdesc limit $offset, $til";
	// Template to use for this page
	$tpl = "latest_frontpage";	
}
else if ($catid>0)
{
	// Category View of Ads
	if (isset($set_general_override))
	{
		// Custom setting from webmaster
		if ($set_general_override>0)
		{
			$til = $set_general_override;			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_general_override;
		}
	}
	//JMR: ID del tipo de operacion para saber que banners mostrar
	$bannerHid = getTipoDeOperacion($catid);
	//JMR
	$categoryPath = getCategoryPath($catid); 
	
	$fixedOrder = "ad_is_premium DESC, ad_is_special DESC, "; //Este orden debe imponerse ante cualquier otro
	
	$sql_string = "select *,$extra_fields_query_addition_fields from $cat_tbl,$usr_tbl,$ads_tbl ".
	"$extra_fields_query_addition_joins $extra_options_mvial_full where cat_id=ad_cat_id AND user_id=ad_owner $val_string ".
	"$lRegionSqlAddon and ad_cat_id=$catid group by ad_id order by $fixedOrder $lToDbOrder $ascdesc limit $offset, $til";
	
	// Template for use for this page
	$tpl = "links";	
	$redirect_tipo_param="&amp;redirecttipo=1";

}
else if (isset($mostviewed))
{
	$fixedOrder = "ad_is_premium DESC, ad_is_special DESC, "; //Este orden debe imponerse ante cualquier otro
	if (isset($set_top_override))
	{
		// Custom setting from webmaster
		if ($set_top_override>0)
		{
			$til = $set_top_override;		
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_top_override;
		}
	}
	$viewsOrder=",ad_views desc";
	$extra_fields_query_addition_fields=0;	
	if(!$lToDbOrder || $lToDbOrder==""){
		$ascdesc ="";
		$viewsOrder="ad_views desc";
	}
		
	$filtroPorMercado="and (cat_fatherid=".ID_CAT_COMPRA." or cat_fatherid=".ID_CAT_ALQUILER." or cat_fatherid in (select cat_id from mvial_category where cat_fatherid=".ID_CAT_COMPRA." or cat_fatherid=".ID_CAT_ALQUILER."))";
	$sql_string = "select *,$extra_fields_query_addition_fields from $cat_tbl,$usr_tbl,$ads_tbl ".
	"$extra_fields_query_addition_joins $extra_options_mvial_full where cat_id=ad_cat_id AND user_id=ad_owner $val_string ".
	"$lRegionSqlAddon ".$filtroPorMercado." group by ad_id order by $fixedOrder $lToDbOrder $ascdesc $viewsOrder  limit $offset, $til";
	
	// Template to use for this page
	$tpl = "mv_mostviewed";
}
else if (isset($latestmode))
{
	$fixedOrder = "ad_is_premium DESC, ad_is_special DESC, "; //Este orden debe imponerse ante cualquier otro
	if (isset($set_latest_override))
	{
		// Custom setting from webmaster
		if ($set_latest_override>0) 
		{
			$til = $set_latest_override;	
			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_latest_override;
		}
	}
	$extra_fields_query_addition_fields=0;
		
	$filtroPorMercado="and (cat_fatherid=".ID_CAT_COMPRA." or cat_fatherid=".ID_CAT_ALQUILER." or cat_fatherid in (select cat_id from mvial_category where cat_fatherid=".ID_CAT_COMPRA." or cat_fatherid=".ID_CAT_ALQUILER."))";
	$sql_string = "select *,$extra_fields_query_addition_fields from $cat_tbl,$usr_tbl,$ads_tbl ".
	"$extra_fields_query_addition_joins $extra_options_mvial_full where cat_id=ad_cat_id AND user_id=ad_owner $val_string ".
	"$lRegionSqlAddon ".$filtroPorMercado." group by ad_id order by $fixedOrder $lToDbOrder $ascdesc ,ad_date desc limit $offset, $til";

	// Template to use for this page
	$tpl = "mv_latest_links";
		
}
else if (isset($best_rated))
{
	// Best Rated Ads Page
	if (isset($set_bestrated_override))
	{
		// Custom setting from webmaster
		if ($set_bestrated_override>0) 
		{
			$til = $set_bestrated_override;	
			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_bestrated_override;
		}
	}
	
	$order = "ad_totalscore";	
	$sql_string = "select *,$extra_fields_query_addition_fields from $cat_tbl,$usr_tbl,$ads_tbl $extra_fields_query_addition_joins where cat_id=ad_cat_id AND user_id=ad_owner $val_string $lRegionSqlAddon group by ad_id order by $order $ascdesc limit $offset, $til";

	
	// Template to use for this page
	$tpl = "bestrated";
}
else if (isset($fav))
{
	// Members Favorite Ads (member area)
	
	if (isset($set_fav_override))
	{
		// Custom setting from webmaster
		if ($set_fav_override>0) 
		{
			$til = $set_fav_override;	
			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_fav_override;
		}
	}
	
	$sql_string = "select *,$extra_fields_query_addition_fields from $cat_tbl, $usr_tbl,$fav_tbl,$ads_tbl $extra_fields_query_addition_joins where cat_id=ad_cat_id AND user_id=ad_owner AND $fav_tbl.f_adid=$ads_tbl.ad_id $val_string AND f_user_id=".$_SESSION["valid_user"]. " $val_string group by ad_id  order by $lToDbOrder $ascdesc limit $offset, $til";
	// Template to use for this page
	$tpl = "fav_links";	
}
else if (isset($my_items))
{
	// Members Favorite Ads (member area)
	
	if (isset($set_myitems_override))
	{
		// Custom setting from webmaster
		if ($set_myitems_override>0) 
		{
			$til = $set_myitems_override;			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_myitems_override;
		}
	}	
	$sql_string = "select *,COALESCE(m3.cat_name,m2.cat_name,m1.cat_name) as tipo,coalesce(pname,'EF_GIF') as pname,mv_package_id from ($cat_tbl m1 left join $cat_tbl m2  On m1.cat_fatherid=m2.cat_id left join $cat_tbl m3 On m2.cat_fatherid=m3.cat_id), (select mv_ad_id,pname,mv_package_id from mvial_ad_extra_options left join mvial_packages on mv_package_id=pid) aux, $ads_tbl, $usr_tbl where m1.cat_id=ad_cat_id  AND ad_owner=user_id AND user_id = ".$_SESSION["valid_user"]. " and aux.mv_ad_id = ad_id order by ad_enabled DESC, $lToDbOrder $ascdesc limit $offset, $til";
	
	$tpl = "my_items_links";
}
else if (isset($useritems) AND !$do_search)
{
	// Members Favorite Ads (member area)
	if (isset($set_myitems_override))
	{
		// Custom setting from webmaster
		if ($set_myitems_override>0) 
		{
			$til = $set_myitems_override;			
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_myitems_override;
		}
	}
	
	$sql_string = "select * from $cat_tbl, $ads_tbl, $usr_tbl where cat_id=ad_cat_id  AND ad_owner=user_id AND user_id = $user_id  $val_string order by $lToDbOrder $ascdesc limit $offset, $til";
	// Template to use for this page
	$tpl = "user_info";
}
else if ($do_search)
{
	//Dialogos de Busqueda
		
	$searchword = getParam("searchword","");	
	$fixedOrder = "ad_is_premium DESC, ad_is_special DESC, "; //Este orden debe imponerse ante cualquier otro
	$main_catId_mb=getParam("main_catId_mb",ID_CAT_COMPRA);
	$mercado = getParam("mercadoC",getParam("mercadoA",""));	
	$marca = getParam("marcaC","");
	$modelo = getParam("modeloC","");
	$anio = getParam("anioC","");	
	$anioDesde = $_REQUEST['anioDesdeC'];
	$anioHasta = $_REQUEST['anioHastaC'];	
	$estado = $_REQUEST['estadoC'];	
	$provincia = getParam("provinciaC",getParam("provinciaA",getParam("provinciaS","")));
	$localidad = getParam("localidadC",getParam("localidadA",getParam("localidadS","")));
	$tipo = getParam("tipoC",getParam("tipoA",getParam("jumpMenu",getParam("catid_search",""))));
	if($main_catId_mb==ID_CAT_SERVICIOS){
		$servicios=true;
	}
    
    foreach (array('searchword', 'do_search', 'Nueva', 'estadoC', 'mercadoC', 'catid_search', 'marcaC', 'modeloC', 'anioDescDeC', 'anioHastaC', 'provinciaC',
        'main_catId_mb', 'mercadoA', 'catid_search', 'provinciaA', 'jumpMenu', 'provinciaS') as $key) {
        if (isset($_REQUEST[$key])) 
            $srch[] = "$key=".$_REQUEST[$key];
    }
    
	$extraSortOrder="&main_catId_mb=$main_catId_mb&".join('&', $srch);
    
	$idCatFiltro  = $main_catId_mb;
	if($tipo!="" && is_numeric($tipo)){
		$filtroPorMercado="and (cat_id=$tipo)";
		//JMR: obterner path de cat		
		$categoryPath = getCategoryPath($tipo);
		//JMR: ID del tipo de operacion para saber que banners mostrar		
		$bannerHid = getTipoDeOperacion($tipo);
	}elseif($mercado!="" && is_numeric($mercado)){		
		$idCatFiltro=$mercado;
		$filtroPorMercado="and (cat_fatherid=$idCatFiltro)";
		//JMR: obterner path de cat
		$categoryPath = getCategoryPath($mercado);
		//JMR: ID del tipo de operacion para saber que banners mostrar		
		$bannerHid = getTipoDeOperacion($mercado);
	}else{
		//JMR: obterner path de cat
		if(empty($searchword)){
			$categoryPath = getCategoryPath($main_catId_mb);
			//JMR: ID del tipo de operacion para saber que banners mostrar		
			$bannerHid = getTipoDeOperacion($mercado);
			$filtroPorMercado="and (cat_fatherid=$idCatFiltro or cat_fatherid in (select cat_id from mvial_category where cat_fatherid=$idCatFiltro))";
		}else{
			$categoryPath = 'Venta y Alquiler';
			//JMR: ID del tipo de operacion para saber que banners mostrar		
			$bannerHid = "ambas";			
			$filtroPorMercado="and (cat_fatherid<>".ID_CAT_SERVICIOS.")";
		}
	}
	/******************************/	
	if($marca!="" && is_numeric($marca))
		$filtroPorMercado .= " and mvial_ad.ad_id in (select sel_option_ad from mvial_selected where sel_option_id=$marca and sel_option_text='marca')";
	
	if($modelo!="")
		$filtroPorMercado .= " and mvial_ad.ad_id in (select sel_option_ad FROM mvial_selected m where m.sel_option_field in  (SELECT q_field FROM mvial_questions m where q_question like 'EF_MODELO' and sel_option_text like '%$modelo%'))";
	
	if($anio!="" && is_numeric($anio))
		$filtroPorMercado .= " and mvial_ad.ad_id in (select sel_option_ad FROM mvial_selected m where m.sel_option_field  in  (SELECT q_field FROM mvial_questions m where q_question like 'EF_ANIO' and sel_option_text='$anio'))";
	
	if($anioDesde!="" && is_numeric($anioDesde))
		$filtroPorMercado .= " AND mv_anio >= $anioDesde";
	
	if($anioHasta!="" && is_numeric($anioHasta))
		$filtroPorMercado .= " AND mv_anio <= $anioHasta";
	
	if($estado != "")
        $filtroPorMercado .= " AND mvial_ad.ad_id IN (SELECT sel_option_ad FROM mvial_selected where sel_option_id IN (SELECT opt_id FROM mvial_options WHERE opt_name = '$estado'))";
	
	if($provincia!="")
		$filtroPorMercado .= " and nombre like '$provincia'";
	
	if($localidad!="")
		$filtroPorMercado .= " and mv_localidad_name like '%$localidad%'";

	if (isset($set_search_override))
	{
		// Custom setting from webmaster
		if ($set_search_override>0) 
		{
			$til = $set_search_override;	
			// To correct the prev/next counter, this correction must also be made
			$set_ads_per_page = $set_search_override;
		}
	}

	$sql_string = "select a.mv_ad_id,
            a.mv_modelo,
            a.mv_potencia,
            a.mv_hskms,
            CAST(a.mv_anio AS SIGNED) AS mv_anio,
            b.marca,
            a.mv_marca_str,
            a.mv_localidad_name,
            a.mv_package_id, mvial_ad.*, mvial_category.*,mvial_user.*,provincia.*,
            $extra_fields_query_addition_fields from 
        mvial_ad INNER JOIN mvial_category ON mvial_ad.ad_cat_id=mvial_category.cat_id
        INNER JOIN mvial_user ON mvial_ad.ad_owner=mvial_user.user_id
        INNER JOIN provincia on provincia.id=mvial_ad.ad_provincia
        LEFT JOIN mvial_ad_extra_options a  ON a.mv_ad_id=mvial_ad.ad_id
        INNER JOIN marca b ON b.id=a.mv_marca
        $extra_fields_query_addition_joins 
        where 1 ";
        
	$lSearchWordDb=strToDb($searchword);
    
    if ($lSearchWordDb) {
        $sql_string = $sql_string . "AND (ad_title like '%$lSearchWordDb%' OR cat_name like '%$lSearchWordDb%' OR marca like '%$lSearchWordDb%' OR mv_marca_str like '%$lSearchWordDb%')";
	}
	
	if ($catid_search)
 	{
 		$catid_search=round($catid_search);
	 	$extra = "catid =". $catid_search;
	 	$lCatidList=getCategoryChildren($catid_search);
	 	
 		if ($lCatidList)
	 		$sql_string = $sql_string . " AND cat_id IN ($lCatidList,$catid_search) ";
	 	else 
	 		$sql_string = $sql_string . " AND cat_id=".$catid_search;
 	
 	}
 	$lReg1=getParam("reg_1","");
 	$lReg2=getParam("reg_2","");
 	$lReg3=getParam("reg_3","");
 	
 	$lRegionId="";
 	if ($lReg3)
 		$lRegionId=$lReg3;
 	else if ($lReg2)
 		$lRegionId=$lReg2;
 	else if ($lReg1)
 		$lRegionId=$lReg1; 	
 	
 	if ($lRegionId>0)
 	{ 		
 		$lRegionId=ereg_replace("_","",$lRegionId);	 
 		$lRegionList=substr(getSubRegions($lRegionId,""),0,-1);
		
 		if ($lRegionList=="")
 			$lRegionList=$lRegionId;
 		else 
 			$lRegionList.=$lRegionList . "," . $lRegionId;
 		
 		$sql_string = $sql_string . " AND ad_region IN ($lRegionList)";
 	}
		$data = "";
		$element = "";
		$str = "";
		$par_list = "";
		$lArray=getExtra();
		$lor=0;
		
		$lSql="select sel_option_ad from $sel_tbl where sel_option_ad is not null AND ( ";
		$lNumFields=0;
		$lBetween=0;
		
		//Marcas de Tiempo
		if(isset($time_start))
			$time_start = microtime(true);
		
		foreach ($_REQUEST as $key => $value) 
		{
			if (ereg("e_", $key) AND $key<>"expire_days" AND !empty($value))
			{
				$lIncludeExtraSearch=1;
				//$lSql.=" AND (";
				//echo $key . "<br />";	
				$lIndex=ereg_replace("e_","",$key);
				$lIndex=ereg_replace("_from","",$lIndex);
				$lIndex=ereg_replace("_to","",$lIndex);
				
				$lThisItem=$lArray[$lIndex];				
				
				if ($lor>0)
						$lSql.=" OR ";					
				
				if ($lThisItem["q_type"]=="s" || $lThisItem["q_type"]=="r")
				{
					if ($lThisItem["q_type"]=="r")
						$value=$value[0];
					
					$lSql.=" (sel_option_id=" . $value . " AND sel_option_field=$lIndex)";
					$lNumFields++;
					$lor++;
					$par_list.="&$key=$value";					
					
				}
				elseif($lThisItem["q_type"]=="t" && $lThisItem["q_between"]==1)
				{
					$lFromKey="e_" . $lIndex . "_from";
					$lToKey="e_" . $lIndex . "_to";
					
					$lFrom=getParamInt($lFromKey,"");
					$lTo=getParamInt($lToKey,"");
					
					$lFrom=ereg_replace(",",".",$lFrom);
					$lTo=ereg_replace(",",".",$lTo);
					
					if ($lFrom>0 && $lTo>0)
					{
						$lSql.=" (sel_option_text BETWEEN $lFrom AND $lTo AND sel_option_field=$lIndex)";
						//$lSql.=" (sel_option_text > $lFrom AND sel_option_text < $lTo AND sel_option_field=$lIndex)";
					
						//echo "From $lFrom To $lTo" . "<br>";					
						$lNumFields++;
						$lor++;
						$lBetween++;
						$par_list.="&$key=$value";
					}
				}
				elseif($lThisItem["q_type"]=="p" && $lThisItem["q_between"]==1)
				{
					$lFromKey="e_" . $lIndex . "_from";
					$lToKey="e_" . $lIndex . "_to";
					
					$lFrom=getParamInt($lFromKey,"");
					$lTo=getParamInt($lToKey,"");
					
					$lFrom=ereg_replace(",",".",$lFrom);
					$lTo=ereg_replace(",",".",$lTo);
					
					if ($lFrom==0)
						$lNumFields++;
					
					if ($lFrom>=0 && $lTo>0)
					{
						$lSql.=" (sel_option_decimal BETWEEN $lFrom AND $lTo AND sel_option_field=$lIndex)";
						//$lSql.=" (sel_option_text > $lFrom AND sel_option_text < $lTo AND sel_option_field=$lIndex)";
					
						$lNumFields++;
						$lor++;
						$lBetween++;
						$par_list.="&$key=$value";
					}
				}
				elseif($lThisItem["q_type"]=="t" || $lThisItem["q_type"]=="d")
				{
					$lSql.=" (sel_option_text like '%" . strToDb($value) . "%' AND sel_option_field=$lIndex)";
					$lNumFields++;
					$lor++;
					$par_list.="&$key=$value";
				}
				elseif($lThisItem["q_type"]=="c")
				{
					$lCount=0;
					$lSql.="  (";
					if (is_array($value))
					{
						$lor++;
						foreach ($value as $lItem)
						{
							if ($lCount>0) // If this is the second option, not the first, add OR between them
								$lSql.=" OR";	
								
							$lCount++;
							$lSql.=" sel_option_id=$lItem";
							$lNumFields++;
							$par_list.="&$key"."[]"."=$lItem";	
						}
					}
					$lSql.=" )";
					//$lNumFields++;
				}
			}
		}
		//Marcas de Tiempo
		if(isset($tiempo)){
			$time_end = microtime(true);
			$tiempo = $tiempo+($time_end-$time_start); 
			//Marcas de Tiempo 
		}
		
		if ($lBetween>0) // Substract with the number of Between fields (since looped twice)
		{
			$lSubstract=round($lBetween/2);
 			$lNumFields=$lNumFields-$lSubstract;
		}
		$lSql.=") group by sel_option_ad having count(*) = $lNumFields";
 		
 		$lExtraIdList="";
 		if ($lNumFields>0)
 		{
			$lResExtraFields=q($lSql);
 		
 			while ($lExRow=mysql_fetch_array($lResExtraFields))
 				$lIdList.=$lExRow["sel_option_ad"] . ",";
			
 			$lIdList=substr($lIdList,0,-1);
 			if ($lIncludeExtraSearch)
 			{ 				
                // If no ad owner has choosen option, add code to stop sql
                $lExtraIdList = ($lIdList=="") ? " AND ad_id IN (0)" : " AND ad_id IN ($lIdList)"; 
 			}
 			else 
 				$lExtraIdList=" "; // Not a extra field search param given, so match all extra fields
 		}
 		if (!$offset)
 			$offset=0;
    
 	//Guardamos en session la consulta para reusarla si alguien pide cambiar el orden
 	if (getParam("Nueva","0")==1 || $_SESSION["searchSQL"]==NULL || $_SESSION["searchSQL"]=="")
    {
 		$_SESSION["searchSQL"] = $sql_string . " $lExtraIdList $val_string $filtroPorMercado group by ad_id order by $fixedOrder";
        
 		$sql_string = $sql_string . " $lExtraIdList $val_string $extraConditions $filtroPorMercado group by ad_id order by $fixedOrder $lToDbOrder  $ascdesc limit $offset, $til";    
 	}
    else
    {
 		$sql_string = $_SESSION["searchSQL"]." $lToDbOrder  $ascdesc limit $offset, $til";
 	}	
	//******************************************************************************** 

	//JMR: cambie el tpl "search_links" por "latest_frontapage"		
	$tpl = "mv_search_links";
}

$sql_resultads = q($sql_string); 

$num_ads =  mysql_num_rows($sql_resultads);

$tplList->assign("NUM_ADS",$num_ads);

/* If not catid given, pretend in order to not break down*/
if ($catid=="")
	$catid=0;

if ($num_ads==0){
	$sql="select cat_allow_ads,cat_name";
	
	if (!empty($_SESSION["la"]) AND $set_multilang_cat)
	{
		$lang_cat = "lang_" . $_SESSION["la"];
		$sql.=",$lang_cat";
		
	}
	$sql.=" from $cat_tbl where cat_id=$catid";
	
	$r_q=q($sql);
	$allow_row=mysql_fetch_array($r_q);
	$catname=$allow_row["cat_name"];
	if (!empty($allow_row["$lang_cat"]))
  		$catname=$allow_row["$lang_cat"];
	$tplList->assign("CATNAME",$catname);
	
	if ($allow_row["cat_allow_ads"]=="on")
		$tplList->assign("ALLOWADS",1);	
}
else 
	$tplList->assign("ALLOWADS",1);	

if (isset($_SESSION["valid_user"]))
	$tplList->assign("IS_LOGGED_IN",1);	

$show_results = "";

// If is frontpage and latest mode is activated, do show link bar
if (!empty($fp) AND empty($latest))
	$not_show_result_nav = 1;
if ($show_results=="")
{
	$adv = "";
	$sp="";
	$s_userid = "";
	$searchword = "";
	$user_ad_id = "";
	$b=0;
	$s_userid = round(getParam("s_userid",""));
	$searchword=getParam("searchword","");
	if (getParam("reg_1",""))
		$sp=$sp. "&amp;reg_1=" . getParam("reg_1","");
	if (getParam("reg_2",""))
		$sp=$sp. "&amp;reg_2=" . getParam("reg_2","");
	if (getParam("reg_3",""))
		$sp=$sp. "&amp;reg_3=" . getParam("reg_3","");
	
	if ($searchword)
		$sp = $sp . "&amp;searchword=$searchword";
	if ($catid_search)
	{
		$sp = $sp . "&amp;catid_search=$catid_search";
		//$catid=$catid_search;
	}
	if ($user_id)
		$sp = $sp . "&amp;user_id=$user_id";
	if ($do_search)
		$sp = $sp . "&amp;do_search=1";
	if ($par_list)
		$sp = $sp . "&amp;par_list=$par_list";
	
	if ($way==1)
	{
		$lImage="layout_images/new/a_down.gif";
		$lWay=0;
	}
	else
	{
		$lImage="layout_images/new/a_up.gif";
		$lWay=1;
	}

	$common_url.= "?catid=$catid$sp";	
	
	$string_actual = strrpos($_SERVER["REQUEST_URI"], "order=");
	if ($string_actual === false){
		$common_url = $_SERVER["REQUEST_URI"] . '/';
	} else {
		$common_url = reverse_strrchr($_SERVER["REQUEST_URI"], '/');
	}
	
	
	if ($order=="ad_title")
			$tplList->assign("image_title","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="cat_name")
			$tplList->assign("image_cat","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="ad_date")
			$tplList->assign("image_date","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="ad_date_expire")
			$tplList->assign("image_expire","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="ad_totalscore")
			$tplList->assign("image_grade","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="picture")
			$tplList->assign("image_picture","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="ad_views")
			$tplList->assign("image_views","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="ad_precio")
			$tplList->assign("image_precio","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="nombre")
			$tplList->assign("image_ubicacion","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");
	else if ($order=="localidad")
			$tplList->assign("image_localidad","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");			
	else if ($order=="marca")
			$tplList->assign("image_brand","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");
	else if ($order=="mv_modelo")
			$tplList->assign("image_model","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");
	else if ($order=="mv_potencia")
			$tplList->assign("image_power","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");
	else if ($order=="mv_hskms")
			$tplList->assign("image_hskms","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");
	else if ($order=="mv_anio")
			$tplList->assign("image_anio","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");	
	else if ($order=="cat_grandfatherid")
			$tplList->assign("image_tipo","<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' />");			
			
	if (is_array($lArrayJoinFields))
	{
		//Marcas de Tiempo
		if(isset($time_start))
			$time_start = microtime(true);
		foreach ($lArrayJoinFields as $lItem) 
		{
	
			$lArrayJoinFields[$lItem["field"]]["url"]="<a href='$common_url&amp;order=".$lItem["id"]."&amp;way=$lWay'  title='".LA_SORT." " . $lItem["caption"] . "'>";
			if ($order==$lItem["id"])
				$lArrayJoinFields[$lItem["field"]]["sort_img"]="<img align='rigth' src='$lImage' alt='".LA_SORT_BY."' title='".LA_SORT_BY."' />";
		}
		//Marcas de Tiempo
		if(isset($tiempo)){
			$time_end = microtime(true);
			$tiempo = $tiempo+($time_end-$time_start); 
			//Marcas de Tiempo 
		}
	} 
	
    if (!strstr($common_url,'?') && strstr($_SERVER['REQUEST_URI'], 'search.php'))
        $common_url.= '?';
        
	$tplList->assign("CATID", $catid);
	//$tplList->assign("CATEGORY_URL", "<a href='$common_url&amp;order=cat_name&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . CATEGORY ."'>");
    $tplList->assign("TITLE_URL", "<a href='$common_url&amp;order=ad_title&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . TITLE ."'>");
	$tplList->assign("AD_URL", "<a href='$common_url&amp;order=ad_title&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . TITLE . "'>");
	$tplList->assign("PRECIO_URL", "<a href='$common_url&amp;order=ad_precio&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . LA_PRICE . "'>");
	$tplList->assign("DATE_URL","<a href='$common_url&amp;order=ad_date&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . DATE_ADDED . "'>");
	$tplList->assign("EXPIREDATE_URL","<a href='$common_url&amp;order=ad_date_expire&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . LA_AD_EXPIRE . "'>");
	$tplList->assign("PICTURE_URL", "<a href='$common_url&amp;order=picture&amp;way=$lWay$extraSortOrder$tablink'>");
	$tplList->assign("ADVIEWS_URL", "<a href='$common_url&amp;order=ad_views&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . AD_VIEWS . "'>");
	$tplList->assign("GRADE_URL", "<a href='$common_url&amp;order=ad_totalscore&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . LA_GRADE . "'>");
	$tplList->assign("UBICACION_URL", "<a href='$common_url&amp;order=nombre&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . EF_PROVINCIA . "'>");
	$tplList->assign("LOCALIDAD_URL", "<a href='$common_url&amp;order=localidad&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . EF_USR_LOCALIDAD . "'>");
	$tplList->assign("MARCA_URL", "<a href='$common_url&amp;order=marca&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . BRAND . "'>");
	$tplList->assign("MODELO_URL", "<a href='$common_url&amp;order=mv_modelo&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . MODEL . "'>");
	$tplList->assign("POTENCIA_URL", "<a href='$common_url&amp;order=mv_potencia&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . POWER . "'>");
	$tplList->assign("HSKMS_URL", "<a href='$common_url&amp;order=mv_hskms&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . HSKMS . "'>");
	$tplList->assign("ANIO_URL", "<a href='$common_url&amp;order=mv_anio&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . ANIO . "'>");
	$tplList->assign("TIPO_URL", "<a href='$common_url&amp;order=cat_grandfatherid&amp;way=$lWay$extraSortOrder$tablink' title='".LA_SORT." " . LAT_TYPE . "'>");
	
	
	
	$tplList->assign("NUM_PER_PAGE", "$set_ads_per_page");
	$tplList->assign("EXTRA_CAPTION_ARRAY",$lArrayJoinFields);
 	$i=0; 	

/***********************FIN CILCO WHILE **********************************/
 // Go through each ad, get fields and field-templates values
//Marcas de Tiempo
if(isset($time_start))
$time_start = microtime(true);
 	
 while ($row=mysql_fetch_array($sql_resultads))
 {
 	$ad_views=0;
 	$ad_votes=0;
 	$ad_totalscore=0;
 	$ad_voters=0;
 	(int) $ad_id = $row["ad_id"];
 	$package_id =  $row["mv_package_id"];
 	$row_extra[]=$row;
 	$lAdList.=$ad_id . ",";
 	$lUserList.=$row["ad_owner"] . ",";
    $ad_title = $row["ad_title"];
	$ad_description = $row["ad_description"];
	$ad_date = formatDateShort($row["ad_date"]);
	$ad_views = $row["ad_views"];
	$ad_votes = $row["ad_votes"];
	$ad_totalscore = $row["ad_totalscore"];
	$ad_voters = $row["ad_voters"];
	$ad_date_expire = formatDateShort($row["ad_date_expire"]);
	$catname = $row["cat_name"];
    $cat_image = $row["cat_image"];
	$name = $row["name"];  
	$email = $row["email"];  
	$vendor_url = $row["user_vendor_url"]; 
    $vendor_homepage = $row["user_vendor_homepage"]; 
	
	$precio = $row["ad_precio"]; 
	$moneda = $row["ad_moneda"]; 
	
    $data = "";
	$element = "";
	$str = "";
	/*EXTRA FIELDS CELLS START*/
    $user_extra_values = '';
    $lExtraValues='';
    
    for ($p = 0 ; $p < $count_extra_fields ; $p++)
    {
    	if ($row["sel_price".$p])
    	{
    		if ($set_currency_text=="USD")	
    			$set_currency_symbol="$ ";
    		else if ($set_currency_text=="EUR")	
    			$set_currency_symbol="� ";
    		else if ($set_currency_text=="NOK")	
    			$set_currency_symbol="kr. ";
    		
        	$lExtraValues[$p]=$set_currency_symbol . " " . PriceFormat($row["sel_option_text".$p]);
    	}
        else 
        	$lExtraValues[$p]=$row["sel_option_text".$p];
    }
    if ($p>0)
    	$fArray[$ad_id]["EXTRA_VALUES"] = $lExtraValues;
    /*EXTRA FIELDS CELLS END*/
	
	
	if (is_array($lExtraFieldArray))
	{		
		//Marcas de Tiempo
		if(isset($time_start))
			$time_start = microtime(true);
		foreach ($lExtraFieldArray as $value)
		{
			if (!is_array($value))
			{
				if (!empty($row[$value]))
				{
					$lArray[$b]["id"]=$ad_id;	
					$lArray[$b]["field"]=$value;
						
					$lArray[$b]["value"]=$row[$value];	
					$b++;
				}
			}
		}
		//Marcas de Tiempo
		if(isset($tiempo)){
			$time_end = microtime(true);
			$tiempo = $tiempo+($time_end-$time_start); 
			//Marcas de Tiempo 			
		}
	}
	$ad_has_picture = $row["ad_has_picture"];
	$ad_is_sold = $row["ad_is_sold"];
	$img_stored = $row["img_stored"];

	
	if (!$ad_voters)
		$ad_voters=0;
		
	if (!$set_list1_color) {
		$set_list1_color = "#FFFFFF";	
	}
	if (!$set_list2_color) {
		$set_list2_color = "#ECF0F6";	
	}
	if ($color == $set_list1_color) {
		$color = $set_list2_color;
	} else {
		$color = $set_list1_color;
	}
	$count_ads++;	
	
	$lCatName="";
	
	// Check if user selected category exists
	if (!empty($_SESSION["la"]) AND $set_multilang_cat)
	{
  		$lang_cat = "lang_" . $_SESSION["la"];
  		if (!empty($row["$lang_cat"]))
  			$lCatName = $row["$lang_cat"];
	}
  	
	// User has not set any prefered language..
	if (!$lCatName)	
	{
		$lang_cat="lang_" . $language;
		if (!empty($row["$lang_cat"]))
  			$lCatName = $row["$lang_cat"]; // Get default language, admin choise
  		else 
  			$lCatName = $row["cat_name"]; // Last resort, use original name..
	}
	$fArray[$ad_id]["CATEGORYNAME"] = $lCatName;
	$fArray[$ad_id]["ad_cat_id"] =  $row["ad_cat_id"];
	$fArray[$ad_id]["cat_fatherid"] =  $row["cat_fatherid"];
	$fArray[$ad_id]["cat_grandfatherid"] =  $row["cat_grandfatherid"];
	$fArray[$ad_id]["CATIMAGE"] = $cat_image;
	$fArray[$ad_id]["DATE_URL"] = "<a href=\"?catid=$catid&amp;=ad_id&amp;searchword=$searchword\">";
	$fArray[$ad_id]["DATEADDED"] = $ad_date;
	$fArray[$ad_id]["EXPIREDATE"] = $ad_date_expire;	
	$fArray[$ad_id]["VIEWED"] = $ad_views;
	$fArray[$ad_id]["SPECIAL"] = $row["ad_is_special"];
    $fArray[$ad_id]["PREMIUM"] = $row["ad_is_premium"];
	$fArray[$ad_id]["COLOR"] = $color;
	$fArray[$ad_id]["LINK"] = linkDetail($ad_id);
	$fArray[$ad_id]["TITLE"] = '<a href="'.linkDetail($row['ad_id']).'">'.$ad_title.'</a>';
	$fArray[$ad_id]["REGDATE"] = $ad_date;
	$fArray[$ad_id]["NUM_VOTERS"] = $ad_voters;
	$fArray[$ad_id]["VENDOR_URL"] = $vendor_url;
	$fArray[$ad_id]["USER_NAME"] = $row["user_name"];
	$fArray[$ad_id]["TIPO"] = $row["tipo"];	
	if($row["pname"]=='EF_GIF')
		$fArray[$ad_id]["pname"] = EF_GIF;
	else
		$fArray[$ad_id]["pname"] = $row["pname"];
	$fArray[$ad_id]["pid"] = $row["mv_package_id"];		
	$fArray[$ad_id]["ID"] = $ad_id;
	$fArray[$ad_id]["user_extra_values"]=$user_extra_values;
	$fArray[$ad_id]["ad_id"] = $ad_id;
	$fArray[$ad_id]["AD_OWNER_NOTIFIED"]=$row["ad_owner_notified"];
	$fArray[$ad_id]["AD_SOLD"]=$row["ad_is_sold"];
	$fArray[$ad_id]["NB"] 	= $i;
	$fArray[$ad_id]["DESCRIPTION"] 	= $ad_description;
	$fArray[$ad_id]["PRECIO"] 	= $precio;
	$fArray[$ad_id]["MONEDA"] 	= $moneda;
	$fArray[$ad_id]["ad_enabled"] 	= $row["ad_enabled"];
	$fArray[$ad_id]["PROVINCIA"] 	= $row["nombre"];
	//Marca es un campo que se comporta a veces como ListBox y otra como editable, por eso el IF
	if((!$row["marca"]) || ($row["marca"]=="")){
		$fArray[$ad_id]["MARCA"] = $row["mv_marca_str"];
	}else{
		$fArray[$ad_id]["MARCA"] = $row["marca"];
	}
	$fArray[$ad_id]["MODELO"] = $row["mv_modelo"];
	$fArray[$ad_id]["POTENCIA"] = $row["mv_potencia"];
	$fArray[$ad_id]["HSKMS"] = $row["mv_hskms"];
	$fArray[$ad_id]["PACKAGE_ID"] = $row["mv_package_id"];
	$fArray[$ad_id]["ANIO"] = $row["mv_anio"];
	$fArray[$ad_id]["LOCALIDAD"] = $row["localidad"];
		
	// Number of holde stars..
	$lStr=getStarRating($ad_totalscore);
	$fArray[$ad_id]["GRADE"]="$lStr";
	
	$lImageHitlist=0;
	$lSkip=0;
	
	if ($fp && !$set_list_img_fp && $set_list_img)
		$lSkip=1;
	
	// Use image hitlist
	if ($set_list_img && !$lSkip)	 
	{				
		$lImageHitlist=1;
		$fArray[$ad_id]["IMAGEYESNO"] = generateImageLinks($ad_id,$ad_has_picture);
	}
	
	// Use default V and X icons for indication of ads
	if (!$lImageHitlist)
	{
		if ($ad_has_picture) {
			$fArray[$ad_id]["IMAGEYESNO"] = "<img src='layout_images/new/yes.gif' align=\"left\" border='0' ";
			$fArray[$ad_id]["IMAGEYESNO"].= "alt=\"".strEnc(dotString($ad_description,50)) . "\" />";
		}
		else 	
		{
			$fArray[$ad_id]["IMAGEYESNO"] = "<img src='layout_images/new/noimg.gif' align=\"left\" border='0' ";
			$fArray[$ad_id]["IMAGEYESNO"].= "alt=\"".strEnc(dotString($ad_description,50)) . "\" />";
		}
	}
	$fArray[$ad_id]["REMOVE"] = "<img src='layout_images/trash.gif' border='0' height='22'";
	$fArray[$ad_id]["REMOVE"].= "alt='$la_remove_fav' align='left' />";
	$fArray[$ad_id]["REMOVE_URL"] = "<a href='fav.php?remove=$ad_id' title='$la_remove_fav'>";
			
	if (isset($my_items)) {
		$fArray[$ad_id]["MODAD_URL"] = "<a href='item.php?ad_id=$ad_id&amp;update_rq=1&amp;catid_edit=$catid' class='thumb_icon' title='". LA_AD_EDIT . "'>";
		$fArray[$ad_id]["MODIMG_URL"] = "<a href='upload_file.php?pic_ad_id=$ad_id' class='thumb_icon' title='".LA_PIC_UPLOAD."'>";	
		$fArray[$ad_id]["CUSTOM"] = "</a>";	
	}
	$lHitListArray[$i]=$row;
	$i++;
	$ad_id++;
 } //End While
 
//Marcas de Tiempo
if(isset($tiempo)){
	$time_end = microtime(true);
	$tiempo = $tiempo+($time_end-$time_start); 
	//Marcas de Tiempo 
}
/***********************FIN CILCO WHILE **********************************/ 
 $lAdList=substr($lAdList,0,-1);
 $lUserList=substr($lUserList,0,-1);
 
 $lExtraArray=getFieldArray($lAdList,$lUserList,",");
 
 //Marcas de Tiempo
if(isset($time_start))
	$time_start = microtime(true);
 foreach ($fArray as $key => $value) 
 {

	$comArray[$key]=$value;
	if ($lExtraArray["ad"][$key])
		$comArray[$key]+=$lExtraArray["ad"][$key];
 }
//Marcas de Tiempo
if(isset($tiempo)){
	$time_end = microtime(true);
	$tiempo = $tiempo+($time_end-$time_start); 
	//Marcas de Tiempo 
}

$tplList->assign("ads",$comArray);
$tplList->assign("users",$lExtraArray["user"]);

$tplList->assign("set_image_program",$set_image_program);
 
// If number of ads is more than one, genereate prev/next links
 if ($num_ads>0)
 {
    $sql_all = preg_replace('/(order|group)\s+by.+$/si', '', $sql_string);
    $sql_all = 'select count(*) '.stristr($sql_all, 'from');
    
    $lTotalCountRes = q($sql_all);
	$num_total = array_shift(mysql_fetch_row($lTotalCountRes));

	if (!isset($par_list))
		$par_list = "";
	
    $csearch = "";	
	if ($catid_search)
		$csearch = "&amp;catid_search=" . $catid_search;
		
	if ($user_id>0)
	{
		$link_bar="user_info.php";
		$link_bar.="?";
	}
	else if ($tpl=="search_links")
	{
		$link_bar.="search.php";
		$link_bar.="?";
	}
 	else if ($tpl=="mv_search_links")
	{
		$link_bar.="search.php";
		$link_bar.="?";
	}
	else if (!$catid_search)
	{
		$link_bar.=linkCat($catid);
		$link_bar.="&amp;";
	}
	else 
		$link_bar.="&amp;";
	
	// Link bar (different file depending what page we are on)
	if ($my_items)
		$link_bar=ereg_replace("index.php","my_items.php",$link_bar);
	elseif ($latestmode)
		$link_bar=ereg_replace("index.php","latestads.php",$link_bar);
	elseif ($mostviewed)
		$link_bar=ereg_replace("index.php","mostviewed.php",$link_bar);	
	elseif ($best_rated)
		$link_bar=ereg_replace("index.php","best_rated.php",$link_bar);	
	
	$link_bar = $link_bar . "order=$order&amp;way=$way&amp;do_search=$do_search&amp;searchword=$searchword$par_list$csearch&amp;user_ad_id=$useritems&amp;user_id=$user_id";
	
	//JMR: Meto la dirección de retorno a cualquier listado en el template
		$tplList->assign("return_link",base64_encode("$link_bar&amp;offset=$offset$tablink".$redirect_tipo_param));
	//END JMR
	
	/*JMR: Esta variable contiene el template generico para navegar en el listado. Solo hay que cambiar el sub-string: "<OFFSET>"
	 *     por el (número de página)*(cantidad de avisos mostrados) y así se generan los links "siguiente", "anterior" y los intermedios
	 * */
	$linkTemplate =  "$link_bar&amp;offset=".OFFSET_TOKEN."$tablink".$redirect_tipo_param;
 	
	if($num_total > $set_ads_per_page){
		$tplList->assign("listOfPages", generateNavegationPages($linkTemplate,floor($offset/$set_ads_per_page),$num_total,$set_ads_per_page,OFFSET_TOKEN));
	}

	if ($offset>0)
	{
		$offset_tmp = $offset;
		$offset = $offset - $set_ads_per_page;
		//$tplList->assign("prev_url",str_replace(OFFSET_TOKEN, $offset, $linkTemplate));
		$tplList->assign("prev_url",str_replace("index.php?",$common_url,str_replace(OFFSET_TOKEN, $offset, $linkTemplate)));
									
		$offset = $offset_tmp;
	}
	if ($num_total > ($offset+$set_ads_per_page))
	{
		$offset = $offset + $set_ads_per_page;
		//$tplList->assign("next_url",str_replace(OFFSET_TOKEN, $offset, $linkTemplate));
		$tplList->assign("next_url",str_replace("index.php?",$common_url,str_replace(OFFSET_TOKEN, $offset, $linkTemplate)));
	}
	
 }
}

$tplList->assign("num_ads_page","$set_ads_per_page");
$tplList->assign("navstr",$navstr);
$tplList->assign("isRegistered",$_SESSION["valid_user"]);
$tplList->assign("servicios",$servicios);
$tplList->assign("main_catId_mb",$main_catId_mb);
//JMR: assign $categoryPath
$tplList->assign("categoryPath",$categoryPath);
//Banner por categoria
$tplList->assign("bannerHid",$bannerHid);

if ($cat_tpl)
{
	if (file_exists("admin/config/templates_new/" . $cat_tpl . ".tpl"))
		$tpl=$cat_tpl;
}
//$tplList->debugging = true;
$tplList->display($tpl . ".tpl");
?>
